package com.village.friend.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.village.friend.constant.MsgCodeEnum;
import com.village.friend.constant.PayStatus;
import com.village.friend.constant.PolicyType;
import com.village.friend.dto.request.UpgradePayDto;
import com.village.friend.dto.request.UserOrderQueryDto;
import com.village.friend.dto.response.BaseResponse;
import com.village.friend.entity.User;
import com.village.friend.entity.UserOrder;
import com.village.friend.entity.UserPolicy;
import com.village.friend.pay.Product;
import com.village.friend.pay.alipay.AliPayServiceImpl;
import com.village.friend.pay.wechat.WxPayServiceImpl;
import com.village.friend.redis.RedisService;
import com.village.friend.service.UserOrderService;
import com.village.friend.service.UserPolicyService;
import com.village.friend.service.UserService;
import com.village.friend.utils.OrderUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 交易订单 前端控制器
 * </p>
 *
 * @author yl
 * @since 2021-08-23
 */
@RestController
@RequestMapping("/appPaymentOrder")
@Slf4j
@Api(tags = "交易订单管理")
public class UserOrderController {
    @Autowired
    private UserOrderService service;
    @Autowired
    private UserPolicyService policyService;
    @Autowired
    private AliPayServiceImpl iAliPayService;
    @Autowired
    private WxPayServiceImpl wxPayServiceImpl;
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserService userService;

    @ApiOperation(value = "分页查询")
    @GetMapping("/list")
    public BaseResponse<IPage<UserOrder>> page(UserOrderQueryDto param) {
        User userRedis = redisService.getUser(param.getToken());
        Integer page = param.getPage();
        Integer limit = param.getLimit();
        if (param == null) {
            return new BaseResponse(MsgCodeEnum.PARAMS_ERROR, null);
        }
        IPage<UserOrder> userOrderIPage = service.pageByParam(page, limit, userRedis.getUid());
        List<UserOrder> records = userOrderIPage.getRecords();
        List<UserOrder> list = new ArrayList<>();
        for (int i = 0; i < records.size(); i++) {
            UserOrder userOrder = records.get(i);
            UserOrder data = new UserOrder();
            data.setId(userOrder.getId());
            data.setUserId(userOrder.getUserId());
            data.setName(userOrder.getName());
            data.setOrderAmount(userOrder.getOrderAmount());
            data.setPayWayName(userOrder.getPayWayName());
            list.add(data);
        }
        userOrderIPage.setRecords(list);
        try {
            return  new BaseResponse(MsgCodeEnum.SUCCESS, service.pageByParam(page, limit, userRedis.getUid())) ;
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResponse(MsgCodeEnum.OTHER_ERROR, e.getMessage());
        }
    }

    /**
     * 会员缴费升级
     *
     * @param param
     * @return
     */
    @ApiOperation(value = "会员缴费升级")
    @PostMapping("/upgradePay")
    public BaseResponse memberUpgradePay(@RequestBody UpgradePayDto param) {
        // 参数校验
        log.info(JSON.toJSONString(param));

        String payType = param.getPayType();
        Integer months = param.getMonths();
        // 判断升级的会员级别
        if (months <= 0) {
            return new BaseResponse(MsgCodeEnum.PARAMS_ERROR, "充值月份异常月份！");
        }
        // 获取用户信息
        User userRedis = redisService.getUser(param.getToken());
        User userEntity = userService.getUserByUserId(userRedis.getUid(), userRedis.getLongitude(), userRedis.getLatitude());

        UserPolicy policy = policyService.findOneByTypeAndMonths(PolicyType.UPGRADE.getType(), months);
        if (policy == null) {
            return new BaseResponse(MsgCodeEnum.OTHER_ERROR, "运营商级别配置未添加，请添加后再升级");
        }
        log.info("会员有效时间：" + months + "个月");
        String orderNo = OrderUtils.getOrderNo("ST");

        BaseResponse response = new BaseResponse(MsgCodeEnum.OTHER_ERROR, "支付方式异常");
        //阿里
        if (payType.equalsIgnoreCase("alipay") || payType.equals("aliAppPay") || payType.equals("aliH5Pay")) {
            response = alipayUpgrade(policy, payType, orderNo);
        } else if (payType.equalsIgnoreCase("wechat")) {//微信
            response = wechatUpgrade(policy, months, orderNo);
        }
        //生成并保存订单
        UserOrder order = OrderUtils.genOrder(userEntity, payType, orderNo, PolicyType.UPGRADE, BigDecimal.valueOf(Double.valueOf(policy.getPrice())), "会员升级缴费", PayStatus.IN_PROCESS);
        service.saveOrUpdate(order);
        return response;
    }

    /**
     * 微信支付升级
     *
     * @param policy
     * @param grade
     * @param orderNo
     * @return
     */
    public BaseResponse<Map<String, String>> wechatUpgrade(UserPolicy policy, Integer grade, String orderNo) {
        // 支付产品
        Product product = genUpgradeProduct(policy.getPrice() + "", "Feel-VIP充值", orderNo);
        return wxPayServiceImpl.wxPay(product);
    }

    /**
     * 阿里支付升级
     *
     * @param policy
     * @param payType
     * @param orderNo
     * @return
     */
    private BaseResponse alipayUpgrade(UserPolicy policy, String payType, String orderNo) {
        // 支付产品
        Product product = genUpgradeProduct(policy.getPrice() + "", "Feel-升级缴费", orderNo);
        if (payType.equals("aliAppPay")) {
            String orderString = iAliPayService.appPay(product);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("payResponse", orderString);
            return new BaseResponse(MsgCodeEnum.SUCCESS, data);
        } else if (payType.equals("aliH5Pay")) {
            String orderString = iAliPayService.aliPayMobile(product);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("payResponse", orderString);
            return new BaseResponse(MsgCodeEnum.SUCCESS, data);
        }
        return iAliPayService.aliPay(product);
    }

    private Product genUpgradeProduct(String amount, String body, String orderNo) {
        Product product = new Product();
        product.setAttach("升级缴费");
        product.setBody(body);
        product.setFrontUrl("https");
        product.setOutTradeNo(orderNo);
        product.setPayWay((Short.parseShort("2")));
        product.setProductId("MemberUp1");
        product.setTotalFee(amount);
        product.setSubject("会员升级缴费");
        product.setIp("192.168.20.11");
        return product;
    }


}

